package club.sanmubird.wechatdemo.controller;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @author Sam
 */
@Slf4j
public class BaseController {


	/**
	 * 参数排序
	 *
	 * @param token
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public String sort(String token, String timestamp, String nonce) {
		String[] strArray = {token, timestamp, nonce};
		Arrays.sort(strArray);
		StringBuilder sb = new StringBuilder();
		for (String str : strArray) {
			sb.append(str);
		}
		return sb.toString();
	}

	/**
	 * 字符串进行shal加密
	 *
	 * @param str
	 * @return
	 */
	public String shal(String str) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			digest.update(str.getBytes());
			byte[] messageDigest = digest.digest();

			StringBuilder hexString = new StringBuilder();
			// 字节数组转换为 十六进制 数
			for (byte aMessageDigest : messageDigest) {
				String shaHex = Integer.toHexString(aMessageDigest & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			log.error("加密过程中出错。", e);
		}
		return "";
	}

}
